package com.cinyi.ormlite.web;

import java.util.Map;
import java.util.ResourceBundle;
import java.util.concurrent.ConcurrentHashMap;

import com.cinyi.ormlite.ConfigurationException;
import com.cinyi.ormlite.IConfiguration;

/**
 * 载入系统配置文件，读取配置属性<br>
 * @author penghui
 *
 */
public class WebConfiguration implements IConfiguration{
	/**
	 * 配置结合
	 */
	private final Map<String,ResourceBundle> bundles =  new ConcurrentHashMap<String,ResourceBundle>();
	
	public WebConfiguration() {
	}

	/**
	 * 添加配置文件
	 * @param bundleName		文件名称
	 * @throws ConfigurationException e
	 */
	public void addBundle(String bundleName) throws ConfigurationException{
		if(bundles.containsKey(bundleName)){
			throw new ConfigurationException(bundleName + " already existed.") ;
		}
		ResourceBundle bundle = java.util.ResourceBundle.getBundle(bundleName);
		bundles.put(bundleName,bundle);
	}
	
	@Override
	public String get(String key) {
		return get(key,null);
	}

	@Override
	public String get(String key, String def) {
		for(Map.Entry<String, ResourceBundle> b : bundles.entrySet()){
			if(b.getValue().containsKey(key)){
				return b.getValue().getString(key);
			}
		}
		return def;
	}

	@Override
	public Integer getInt(String s, Integer def) {
		String val = get(s);
		if(val == null ) {
			return def ;
		}
		
		try{
			return Integer.parseInt(val);
		}catch(NumberFormatException ne){
			return def ;
		}
	}

	@Override
	public Double getDouble(String s, Double def) {
		String val = get(s);
		if(val == null ) {
			return def ;
		}
		
		try{
			return Double.parseDouble(val);
		}catch(NumberFormatException ne){
			return def ;
		}
	}

	@Override
	public Long getLong(String s, Long def) {
		String val = get(s);
		if(val == null ) {
			return def ;
		}
		
		try{
			return Long.parseLong(val);
		}catch(NumberFormatException ne){
			return def ;
		}
	}

	@Override
	public boolean getBoolean(String key, boolean b) {
		String bs = get(key);
		if(bs != null && ("true".equalsIgnoreCase(bs)||"yes".equalsIgnoreCase(bs)||"y".equalsIgnoreCase(bs))){
			return true ;
		}
		return false;
	}
	
	/**
	 * 获取具体的资源文件
	 * @param name	资源文件名
	 * @return b
	 */
	public ResourceBundle getBundle(String name){
		return bundles.get(name);
	}
	
}
